
import java.util.HashSet;
import java.util.Set;

public class MagicSquareProcessor2 {

    private static final int SIZE = 9; // 幻方大小
    private static final int[][] MAGIC_SQUARE = {
            {47, 58, 69, 80, 1, 12, 23, 34, 45},
            {57, 68, 79, 9, 11, 22, 33, 44, 46},
            {67, 78, 8, 10, 21, 32, 43, 54, 56},
            {77, 7, 18, 20, 31, 42, 53, 55, 66},
            {6, 17, 19, 30, 41, 52, 63, 65, 76},
            {16, 27, 29, 40, 51, 62, 64, 75, 5},
            {26, 28, 39, 50, 61, 72, 74, 4, 15},
            {36, 38, 49, 60, 71, 73, 3, 14, 25},
            {37, 48, 59, 70, 81, 2, 13, 24, 35}
    };

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis(); // 记录开始时间
        Set<Integer> visited = new HashSet<>();
        int sum = 0;

        // 处理从41右向上的路径
        sum += processDirection(4, 4, 1, visited);
        // 处理从41右向下的路径
        sum += processDirection(4, 4, 3, visited);

        // 处理三角形区域内的其他数字
        sum += processTriangleRegion(visited);
        long endTime = System.currentTimeMillis(); // 记录结束时间
        long duration = endTime - startTime; // 计算运行时间
        System.out.println("所有被7整除的数字的数字和: " + sum);
        System.out.println("程序运行时间: " + duration + " 毫秒");
    }

    private static int processDirection(int x, int y, int direction, Set<Integer> visited) {
        int sum = 0;
        while (x >= 0 && y >= 0 && x < SIZE && y < SIZE) {
            int value = MAGIC_SQUARE[y][x];
            if (!visited.contains(value) && value % 7 == 0) {
                System.out.println("被7整除的数字: " + value);
                sum += value;
                visited.add(value);
            }
            switch (direction) {
                case 1:
                    x++;
                    y--;
                    break;
                case 3:
                    x++;
                    y++;
                    break;
            }
        }
        return sum;
    }

    private static int processTriangleRegion(Set<Integer> visited) {
        int sum = 0;

        // 遍历三角形区域内的所有点
        for (int y = 0; y < SIZE; y++) {
            for (int x = 0; x < SIZE; x++) {
                if (isInTriangle(x, y) && !visited.contains(MAGIC_SQUARE[y][x]) && MAGIC_SQUARE[y][x] % 7 == 0) {
                    int value = MAGIC_SQUARE[y][x];
                    System.out.println("被7整除的数字: " + value);
                    sum += value;
                    visited.add(value);
                }
            }
        }

        return sum;
    }

    private static boolean isInTriangle(int x, int y) {
        // 判断点 (x, y) 是否在三角形区域内
        // 三角形的边界由 (4, 4) 到 (8, 0) 和 (4, 4) 到 (8, 8) 组成
        // 包括最右边一列
        return (y - 4 <= x - 4) && (y - 4 >= -(x - 4)) || (x == 8 && y >= 0 && y <= 8);
    }
}